package com.huawei.imedia.it.utils;

import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: tsx
 * @Date: 2021/8/29 - 08 - 29 - 9:37 下午
 * @Description: com.huawei.imedia.it.utils
 * @version: 1.0
 */
@WebListener
public class BindingListener implements HttpSessionBindingListener {
    String username;
    public BindingListener(String username){
        this.username=username;
    }

    public void valueBound(HttpSessionBindingEvent event) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = event.getSession();
        System.out.println(session.getId());
        ServletContext application = session.getServletContext();
        session.setAttribute("username","tsx");
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 登录账户
        String username = request.getParameter("username");

        String hisUserName = session.getAttribute("username").toString();

        List onlineUserList = (List) application.getAttribute("onlineUserList");

        if ((StringUtils.isNotBlank(hisUserName) && !hisUserName.equals(username))
                || CollectionUtils.isEmpty(onlineUserList)) {
            // 把登录账户名保存至session
            session.setAttribute("username", username);
            // 把登录账户名放入在线列表

            if (null == onlineUserList) {
                onlineUserList = new ArrayList();
                application.setAttribute("onlineUserList", onlineUserList);
            }
            onlineUserList.add(username);
        }

        System.out.println("当前在线人数：" + onlineUserList.size());
    }

    public void valueUnbound(HttpSessionBindingEvent event) {
        HttpSession session = event.getSession();
        ServletContext application = session.getServletContext();

        // 登录账户
        String username = (String) session.getAttribute("username");

        // 从在线列表中删除登录账户名
        List onlineUserList = (List) application.getAttribute("onlineUserList");
        onlineUserList.remove(username);

        System.out.println(username + "退出系统");
        System.out.println("当前在线人数：" + onlineUserList.size());

    }
}
